package cn.test.rabbitmq.normal;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeoutException;

/**
 * @author hanchao
 * @date 2017/6/30 15:00
 */
public class DefaultDirectConsumer {
    private static final String QUEUE_NAME = "test-queue";
    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.1.170");
        factory.setUsername("admin");
        factory.setPassword("admin");
        factory.setVirtualHost("han");
        Connection connection = factory.newConnection();
        final Channel channel = connection.createChannel();
        channel.exchangeDeclare("dir",BuiltinExchangeType.DIRECT);

        AMQP.Queue.DeclareOk dc = channel.queueDeclare(QUEUE_NAME, false, false, false, null);


        //auto ack下，即使异常，也会确认消息。所以在spring中，只能靠spring的未处理来死循环消息
        channel.basicConsume(QUEUE_NAME, false, "tag", new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println(new String(body));
                System.out.println(consumerTag);
                //channel.basicReject(envelope.getDeliveryTag(),true);
                System.out.println(envelope.isRedeliver());
                Map<String, Object> headers = properties.getHeaders();
                if(properties.getHeaders() == null){
                    headers.put("_redeliverTimes",1);
                }else{
                    System.out.println(headers.get("_redeliverTimes"));
                }
                System.out.println(envelope.getDeliveryTag());
                System.out.println(properties);
                channel.basicReject(envelope.getDeliveryTag(),true);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });


    }
}
